<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-07-21 14:35:42
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-16 18:00:39
 * @FilePath     : \rpms\src\views\project\create\components\member.vue
-->
<template>
  <el-button
    v-if="!isApproval"
    @click="handleAdd"
    class="btnClass"
    type="primary"
    icon="el-icon-plus"
  />
  <el-table
    :data="model.tableData"
    border
    style="width: 100%"
    :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
  >
    <template #empty>
      <el-empty :image-size="50" description="暂无数据"></el-empty>
    </template>
    <el-table-column type="index" label="序号"> </el-table-column>
    <el-table-column prop="name" label="姓名"></el-table-column>
    <el-table-column prop="department" label="单位"></el-table-column>
    <el-table-column label="操作" v-if="!isApproval">
      <template #default="{ row, $index }">
        <el-button type="text" @click="handleEdit(row, $index)">{{
          String(row.id) === model.leader || String(row.id) === model.owner
            ? ""
            : "编辑"
        }}</el-button>
        <el-popconfirm
          confirm-button-text="确定"
          cancel-button-text="取消"
          icon="el-icon-info"
          icon-color="red"
          title="确定删除该条记录吗？"
          @confirm="handleDelete(row, $index)"
        >
          <template #reference>
            <el-button type="text">{{
              String(row.id) === model.leader || String(row.id) === model.owner
                ? ""
                : "删除"
            }}</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
    :title="model.isEdit ? '修改项目团队成员' : '添加项目团队成员'"
    v-model="model.dialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <el-form
      :model="model.formData"
      ref="formRef"
      @submit.prevent
      :rules="model.formRules"
      label-width="100px"
    >
      <el-row>
        <el-col>
          <el-form-item label="姓名" prop="name">
            <el-select
              v-model="model.formData.user"
              style="width: 100%"
              filterable
              clearable
              remote
              placeholder="请输入姓名搜索"
              :remote-method="getTableLeaderData"
              value-key="id"
              @change="changeLeader"
            >
              <el-option
                id="default-option"
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="单位" prop="department">
            <el-input
              disabled
              v-model.trim="model.formData.department"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row justify="end">
      <el-button @click="model.dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, watch } from "vue";
import { getAbutmentList} from "/@/api/expert";
import { cloneDeep } from "lodash-es";
import { useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
export default defineComponent({
  name: "Goal",
  props: {
    data: {
      type: Array,
      default: () => []
    },
    leader: {
      type: String
    },
    owner: {
      type: String
    }
  },

  setup(props, ctx) {
    console.log(props, ctx);
    const route = useRoute();
    const isApproval = route.query.mode === "approval" ? true : false;
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const userList = ref([]);
    const model = reactive({
      index: 0,
      isEdit: false,
      dialogFormVisible: false,
      tableData: [],
      formData: {
        isEmp: "",
        name: "",
        leader: true,
        user: null,
        userId: "",
        department: "",
        ext1: ""
      },
      formRules: {
        name: [{ required: true, message: "请选择成员", trigger: "change" }],
        ext1: [{ required: true, message: "请输入承担角色", trigger: "change" }]
      },
      leader: "",
      owner: ""
    });
    const handleSubmit = async () => {
      const isValid = await new Promise(resolve =>
        formRef.value.validate(resolve)
      );
      if (!isValid) return;
      if (model.isEdit) {
        model.tableData[model.index] = cloneDeep(model.formData);
      } else {
        if(model.tableData?.length){
          const dataIdx = model.tableData.findIndex((item) => item.userId === model.formData.userId);
          if(dataIdx != -1){
            NotifMessage.warning("请勿重复添加");
            return
          }
          model.tableData.push(model.formData);
        }
        else{
          model.tableData.push(model.formData);
        }
      }

      model.tableData.forEach(el => {
        el.name = el.name.split("-")[0];
      });
      model.dialogFormVisible = false;
    };
    const handleAdd = () => {
      model.formData = {
        isEmp: "",
        name: "",
        leader: true,
        user: null,
        userId: "",
        department: "",
        ext1: ""
      };
      model.isEdit = false;
      model.dialogFormVisible = true;
    };

    const handleEdit = (row, index) => {
      model.dialogFormVisible = true;
      model.isEdit = true;
      model.index = index;
      model.formData = cloneDeep(row);
      userList.value = [row.user];
    };

    const handleDelete = (row, index) => {
      model.tableData.splice(index, 1);
    };

    async function getTableLeaderData(query = "") {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          nameLike: query,
          deptNameLike: "",
          pageNum: 1,
          pageSize: 200,
          querySource: 1
        };
        const { code, data } = await getAbutmentList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return {
              id: item.userId,
              name: item.name + (item.deptName ? "-" + item.deptName : "-无"),
              deptName:item.deptName
            };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    //选择人员
    const changeLeader = item => {
      if (item !== "") {
        model.formData.department = item.deptName;
        model.formData.name = item.name;
        model.formData.userId = item.id;
        model.formData.isEmp = item.isEmp;
      }
    };

    onMounted(() => {
      model.tableData = props.data || [];
    });

    watch(
      () => [props.data, props.leader, props.owner],
      ([newvalue, v1, v2]) => {
        model.tableData = (newvalue || []) as any;
        model.tableData.forEach(el => {
          el.id = el.userId;
          el["user"] = {
            id: el.id,
            name: el.name.split("-")[0]
          };
        });
        model.leader = v1 as string;
        model.owner = v2 as string;
      },

      { immediate: false }
    );

    return {
      isApproval,
      changeLeader,
      userList,
      model,
      formRef,
      handleSubmit,
      handleAdd,
      handleEdit,
      handleDelete,
      getTableLeaderData
    };
  }
});
</script>
<style lang="scss" scoped>
.btnClass {
  margin-bottom: 10px;
}
</style>
